package ar.com.age.distribuidora.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.age.distribuidora.dao.AjusteDao;
import ar.com.age.distribuidora.dominio.Ajuste;

@Component
public class AjusteHibernateDao implements AjusteDao {

	private SessionFactory sessionFactory;

	@Autowired(required = true)
	public void setSessionFactory(SessionFactory factory) {
		this.sessionFactory = factory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public Ajuste saveOrUpdate(Ajuste ajuste) {
		if (ajuste.getId() == null) {
			getCurrentSession().save(ajuste);
		} else {
			getCurrentSession().update(ajuste);
		}
		return ajuste;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Ajuste> getAll() {
		
		Query query = getCurrentSession().createQuery(
				"from " + Ajuste.class.getName());
		return query.list();
	}

	@Override
	public void physicalDelete(Ajuste ajuste){
		
		getCurrentSession().delete(ajuste);
				
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Ajuste> find(String codigo, String lote, Date desde, Date hasta){
		
		List<Ajuste> ajustes = null;
		Criteria criteria = getCurrentSession().createCriteria(Ajuste.class);
				
		if(codigo != "")
			criteria.add(Restrictions.like("codigo", "%"+codigo+"%"));
		if(lote != "")
			criteria.createCriteria("loteDeCompra", "lote").add(Restrictions.like("codigo", "%"+lote+"%"));
		if(desde != null)
			criteria.add(Restrictions.ge("fecha", desde));
		if(hasta != null)
			criteria.add(Restrictions.le("fecha", hasta));
				
		ajustes = criteria.list();
		
		return ajustes;
	}
}
